package Controllers;


import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import Boundry.LoginPanel;
import Boundry.Splash;
import Controllers.GenericToolsForController.WorkerRolls;
import Entity.Message;
import Entity.User;
import Entity.Worker;


public class UsersManager implements ActionListener
{
	private Splash splash;
	private LoginPanel loginPanel;
	
	
	private String userName;
	private String password;
	private static int userID  ;
	private static boolean bNotFinisehdflag=true;
	private static boolean passedUserTest;
	private static boolean killTheThread;
	  private boolean isAllreadyLogged = false;
	private Message answerMessage;
	
	
	private static  UsersManager Instance = null;
	private UsersManager(){}
	public static UsersManager getInstance()
	{
		if(Instance == null)
		{
			Instance = new UsersManager();
		}
		return Instance;
	}
	
	
	
	public void login()
	{
		loginPanel = new LoginPanel();
        GlobalData.guiMangaer.switchScreen(loginPanel);
        setListener(loginPanel);	
	}
	
	
	
	private void setListener(LoginPanel loginPanel2) 
	{
		loginPanel.btnLog.addActionListener(this);
		loginPanel.btnClear.addActionListener(this);	
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == loginPanel.btnLog)
		{	
			userName = loginPanel.getUserName();
			password = loginPanel.getUserPassword();
			if(userName == null || userName.length()==0 )
			{
				loginPanel.showNameError();
				loginPanel.clearNameField();
			}
			else if(password == null || password.length()==0  )
			{
				loginPanel.showPasswordError();
				loginPanel.clearPasswordField();
			}
			else
			{
				
				SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
				{
					@Override
					 public Void doInBackground() 
					 {
						splash = new Splash();
						splash.setInfo("Logging In");
						boolean cond = checkUserAndPassword(userName,password);
						
						//System.out.println(checkUserAndPassword(userName,password)==true);
						if (isAllreadyLogged)
						{
							JOptionPane.showMessageDialog(splash,"User All ready logged from another client", "Error",JOptionPane.ERROR_MESSAGE);
							return null;
						}	
						if ( cond == true )
						{
								System.out.println("cond == true");
								GlobalData.guiMangaer.showHelpAndUserPanel();
								
								GlobalData.guiMangaer.setUserName(GlobalData.user.getUsername());
								
								
								if (GlobalData.worker != null)
								{
									if (WorkerRolls.ADMINISTATION ==GlobalData.worker.getRole())
									{
										GUIControllerWorker.getInstance().inizializtion();
									}
									else if (WorkerRolls.ICM_MANGER == GlobalData.worker.getRole())
									{
										GUIControllerICMManager.getInstance().inizializtion();
									}
									else if(WorkerRolls.IE == GlobalData.worker.getRole())
									{
										GUIControllerWorker.getInstance().inizializtion();
									}
								}
								else
								{
									GUIControllerUser.getInstance().inizializtion();
								}
								
						}
						else
						{
							splash.setVisible(false);
							JOptionPane.showMessageDialog(new JFrame(),"Wrong User Name", "Error",JOptionPane.ERROR_MESSAGE);

							System.out.println("invalid");
							loginPanel.clearPasswordField();
							loginPanel.clearNameField();
							loginPanel.disappearNameError();
							loginPanel.disappearshowPasswordError();
						  //invalid
						}	
					//	System.out.println("no!!!!!!!!!!!!!!");
						return null;
					}
					@Override
					public void done() 
					{
						splash.setVisible(false);
							
						
					}
				    };  
				worker.execute();
			   
			}
			
		}
		else if(e.getSource() == loginPanel.btnClear)
		{
			loginPanel.clearPasswordField();
			loginPanel.clearNameField();
			loginPanel.disappearNameError();
			loginPanel.disappearshowPasswordError();
		}
	}
	
	
	
	
	
	public User getUserByID(int userID) 
	{
		
		return null;	
	}
	
	
	
	
	
	public User[] getAllUsers() 
	{
		
		return null;
	}
	
	public boolean checkUserAndPassword(String userName ,String password )
	{
		final String[] datauser = {userName,password}; 
		passedUserTest = false;	
		killTheThread = false;
		isAllreadyLogged=false;
		final Thread taskToDo = new Thread() {
		  

			@Override public void run() 
		    {  
		    	 try 
	                {
		    		    Message msg = new Message(11001, GlobalData.MESSAGE_ID(), datauser);
		    		    while (passedUserTest == false && killTheThread == false)
		    		    {
			    		    GlobalData.client.sendToServer(msg);
		        			try 
		        			{
		        				Thread.sleep(1000);
		        			} 
		        			catch (InterruptedException e) {
		        				// TODO Auto-generated catch block
		        				e.printStackTrace();
		        			}
	        				if (GlobalData.client.isRecivedMessage()==true)
	        				{
	        					answerMessage = (Message)GlobalData.client.getAnsweredMessage(msg);
	        					
	        				    if (answerMessage!=null)
	        				    {
	        				    	if (((User)answerMessage.getDataGram()).isAllReadyLoggedIn())
	        				    	{
	        				    		
	        				    		isAllreadyLogged=true;
	        				    		//passedUserTest = false;
	        				    		//throw new Exception();
	        				    	}
	        				    	else
	        				    	{ 
	        				    	if(answerMessage.getDataGram() instanceof User)
		        				    	{
		        				    		GlobalData.user = (User)answerMessage.getDataGram();
		        				    		GlobalData.worker = null;
		        				    	}
		        				    	if(answerMessage.getDataGram() instanceof Worker)
		        				    	{
		        				    		GlobalData.worker = (Worker)answerMessage.getDataGram();
		        				    		GlobalData.user =  (Worker)answerMessage.getDataGram();
		        				    	}
		        					}
	        				    	passedUserTest = true;
		        				}
		        			}
		    		    }
	                } 
	                catch (Exception e) 
	                {
	                	splash.setVisible(false);
	                    throw new RuntimeException(e);
	                }
		    }
		};
		System.out.println("bla bla ");
		taskToDo.start();
		
		int timeOut =  10000; // time in milisecond
		int timePerIteration = 30; // time in milisecond
		 while (passedUserTest == false)
		 {
				try {
					timeOut-= timePerIteration;
					Thread.sleep(timePerIteration);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(timeOut<=0)
				{
					System.out.println("TimeoutException ");
					killTheThread = true;
					System.out.println("taskToDo.isAlive() = " + taskToDo.isAlive());
					return passedUserTest;
				}
		 } 
		return passedUserTest;
	}

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GuiManager guiMangaer = new GuiManager();
					GlobalData.guiMangaer = guiMangaer;
					UsersManager.getInstance().login();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	public ArrayList<User> getAllUsersNonWorkers() {
		// TODO Auto-generated method stub
		Message msg = new Message(11002, GlobalData.MESSAGE_ID(), null);
		
		Message AnswerMessage = null;
		
		try 
		{
			GlobalData.client.sendToServer(msg);
			Thread.sleep(500);
			while (true)
			{
				if (GlobalData.client.isRecivedMessage()==true)
				{
					AnswerMessage = GlobalData.client.getAnsweredMessage(msg);
				    if (AnswerMessage!=null)
				  	      break;
				}	
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch ( InterruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ( ArrayList<User>) AnswerMessage.getDataGram();
		
		
		
	}
	public boolean logoff(int userId2) {
		Message msg = new Message(11003, GlobalData.MESSAGE_ID(), userId2);
		
		Message AnswerMessage = null;
		
		try 
		{
			GlobalData.client.sendToServer(msg);
			Thread.sleep(500);
			while (true)
			{
				if (GlobalData.client.isRecivedMessage()==true)
				{
					AnswerMessage = GlobalData.client.getAnsweredMessage(msg);
				    if (AnswerMessage!=null)
				  	      break;
				}	
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch ( InterruptedException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (AnswerMessage==null)
			return false;
		if (AnswerMessage.getDataGram() instanceof Boolean)
		{
			System.out.println("Logoff: "+(Boolean)AnswerMessage.getDataGram());
			return (Boolean)AnswerMessage.getDataGram();
		}
		return false;
		// TODO Auto-generated method stub
		
	}
}
/*	userType=3;   //need to change this to exact type

switch  (userType)   {

case 1:        // for worker
	 GlobalData.guiMangaer.switchScreen(new WorkerPanel());
	 this.setVisible(false);	
	 break;
	
case 2:        // for regular user as student
	GlobalData.guiMangaer.switchScreen(new UserPanel());
	this.setVisible(false);
	break;
	
case 3:			// for ISM Manager
	GlobalData.guiMangaer.switchScreen(new ISMPanel());
	this.setVisible(false);
	break;
	
}*/

